package com.googlecode.garbagecan.dbtest.benchmark;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class Benchmark {
	public static void main(String[] args) throws Exception {
//		Benchmark b = new Benchmark();
//		b.createTables();
//		b.insert();
//		b.dropTables();
		
		BenchmarkJob job = new BenchmarkJobForPostgreSQL();
		try {
			job.setUp();
		} catch(BenchmarkException ex) {
			ex.printStackTrace();
		}
		try {
			job.run();
		} catch(BenchmarkException ex) {
			ex.printStackTrace();
		}
		try {
			job.tearDown();
		} catch(BenchmarkException ex) {
			ex.printStackTrace();
		}
	}
	
	private void createTables() throws Exception {
		String file = TestInsert.class.getResource("/com/googlecode/garbagecan/dbtest/benchmark/create.sql").getFile();
		List<String> sqls = FileUtils.readLines(new File(file));
		Connection conn = DBUtil.getConnection();
		for (String sql : sqls) {
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.executeUpdate();
			ps.close();
		}
		conn.close();
	}
	
	private void dropTables() throws Exception {
		String file = TestInsert.class.getResource("/com/googlecode/garbagecan/dbtest/benchmark/drop.sql").getFile();
		List<String> sqls = FileUtils.readLines(new File(file));
		Connection conn = DBUtil.getConnection();
		for (String sql : sqls) {
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.executeUpdate();
			ps.close();
		}
		conn.close();
	}
	
	private void insert() throws Exception {
		Connection conn = DBUtil.getConnection();
		for (int i = 0; i < 10; i++) {
			insert(conn);
		}
		conn.close();
	}
	
	private void insert(Connection conn) throws Exception {
		long start = System.currentTimeMillis();
		String sql = "INSERT INTO T1(ID, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10)values(?,?,?,?,?,?,?,?,?,?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		int length = 10000;
		for (int i = 0; i < length; i++) {
			for (int colIdx = 1; colIdx <= 11; colIdx ++) {
				ps.setObject(colIdx, "12345678901234567890_" + colIdx);
			}
			ps.addBatch();
		}
		ps.executeBatch();
		ps.clearBatch();
		ps.close();
		conn.commit();
		
		long stop = System.currentTimeMillis();
		System.out.println("Time: " + (stop - start));
	}
	
	private void prepareConnection(Connection conn) throws Exception {
		String sql = " select version()";
		PreparedStatement ps = conn.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			System.out.println(rs.getString(1));
		}
		rs.close();
		ps.close();
	}
}
